﻿using Core.Tools.IOC;
using Prism.Events;
using Prism.Modularity;
using Prism.Regions;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using UI.Application.Initialize.Services;
using UI.Application.Share.Names;

namespace UI.Application.Initialize.ViewModels
{
    internal class InitializeViewModel:ReactiveObject
    {
        private HardwareManager HardwareManager { get; }
        //private IModuleManager ModuleManager {  get; }
        //private IRegionManager RegionManager { get; }
        

        /// <summary>
        /// 前端显示加载信息
        /// </summary>
        [Reactive]
        public string Message { get; set; } = string.Empty;
        [Reactive]
        public Visibility ButtonVisibility {  get; set; }= Visibility.Collapsed;


        public ICommand InitCommand { get;  }
        public ICommand EnterCommand { get; }
        public InitializeViewModel(HardwareManager hardwareManager)
        {
            //ModuleManager = moduleManager;//这里用了PrismProvider，所以不需要这个了
            //RegionManager= regionManager;
            InitCommand = ReactiveCommand.Create(InitAsync);
            EnterCommand = ReactiveCommand.Create(Enter);
            //hardwareManager = new HardwareManager(eventAggregator);//没有对象就new一个
            HardwareManager = hardwareManager;

        }

        private async void InitAsync()
        {
            ButtonVisibility = Visibility.Collapsed;
            if(!HardwareManager.Initialized)
            {
                Message = "正在初始化硬件";
                var result=await HardwareManager.InitAsync();
                if(!result.Success)
                {
                    Message=result.Message;
                    ButtonVisibility = Visibility.Visible;
                    return;
                }

            }
            Message = "初始化完成";
            Thread.Sleep(2000);
            Enter();
        }
        //异步 async
        private async void Enter()
        {
            await Task.Delay(250).ContinueWith(p =>
            {
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    PrismProvider.ModuleManager.LoadModule(ModuleNames.ApplicationMainModule);
                    PrismProvider.RegionManager.RequestNavigate(RegionNames.MainRegion, ViewNames.MainView);
                });
            });
        }

    }
}
